#include "栈.h"

/*typedef struct STACK
{
	int* a;
	int size;	
	int capacity;
}ST;
*/

void STInit(ST* stack)//初始化
{
	stack->a = (int*)malloc(sizeof(int) * 4);
	if (stack->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	stack->size = -1;
	stack->capacity = 4;
}

void STPrint(ST* stack)//打印栈顶数据（不取出）
{
	assert(stack);
	if (stack->size == -1)
	{
		printf("栈为空\n");
		return;
	}
	printf("%d ", stack->a[stack->size]);
}

void STDestroy(ST* stack)//销毁栈
{
	assert(stack);
	stack->size = 0;
	stack->capacity = 0;
	free(stack->a);//先释放掉a指向的空间
	stack->a = NULL;//再释放a本身
}

void PopST(ST* stack)//删除栈顶元素
{
	assert(stack);
	if (stack->size == -1)
	{
		printf("栈为空\n");
		return;
	}
	(stack->size)--;
}

void PushST(ST* stack, int x)//放入元素
{
	assert(stack);
	if (stack->size == (stack->capacity) - 1)
		//判断栈是否为满，满的话则进行扩容
	{
		int* tmp = (int*)realloc(stack->a, sizeof(int) * (stack->capacity) * 2);
		if (tmp == NULL)
		{
			perror("malloc fail");
			return;
		}
		stack->a = tmp;
		stack->capacity *= 2;
	}

	(stack->size)++;
	stack->a[stack->size] = x;
}

int Size(ST* stack)//查看目前栈的大小
{
	return stack->size;
}

bool STEmpty(ST* stack)//判断是否为空
{
	assert(stack);
	return stack->size == -1;
}

int STTop(ST* stack)//取出栈顶元素
{
	if (!stack)
	{
		printf("栈为空，无法取出元素\n");
		return;
	}
	return stack->a[stack->size];
}